//
//  MyDocument.m
//  blipTest
//
//  Created by dawid on 08-12-11.
//  Copyright __MyCompanyName__ 2008 . All rights reserved.
//

#import "AppController.h"
#import "BlipRequestUpdate.h"

#import "BlipMessage.h"
#import "MessageView.h"
#import "RegexKitLite.h"
#import "AGKeychain.h"
#import "NSData-Base64Extensions.h"
#import "BlipErrors.h"

#import "JSON/JSON.h"
#include <Carbon/Carbon.h>
#import "CGSPrivate.h"
#import "QuickLook.h"

#import "DownloadUpdatesOperation.h" 
#import "DownloadSubscriptionOperration.h"
#import "SendMessageOperation.h"

#define QLPreviewPanel NSClassFromString(@"QLPreviewPanel")

#define PrivateMessagesVisible 1
#define AllMessagesVisible 0
#define SLOW_MOTION_COUNT 3
#define DOCUMENTVIEW_ADD_PIXEL 25
#define USER_PATH_NAME @"tracked_user_path"
#define RECIPIENT_DOESNT_EXIST @"nieistniejacy_odbiorca"


//Becasuse sometime there is a problem with ifMatchedblabla Regexp, I've created that fix
@interface NSString (Dummy)

- (NSString*)stringValue;

@end

@implementation NSString (Dummy)

- (NSString*)stringValue {
  return self;
}

@end


@interface MyPreviewItem : NSObject {
  NSURL* previewItemURL;
}

@property (nonatomic, retain) NSURL* previewItemURL;

@end

@implementation MyPreviewItem

@synthesize previewItemURL;

@end


@implementation AppController
@synthesize textBox;
@synthesize opacity;
@synthesize maxMessagesShow;
@synthesize refreshInterval;
@synthesize lastUpdateId;
@synthesize messagesTypeVisible;
@synthesize userPassword;
@synthesize hideAfterSendMsg;
@synthesize allBlipsButton;
@synthesize isFirstRun;
@synthesize textBoxBocked;
@synthesize userNames;
@synthesize hideGrowlNotif;
@synthesize hideIconBadge;
@synthesize blipMessages;
@synthesize shortKeyCall;
@synthesize showYoutube;

static AppController *shared;
extern OSStatus CGSNewConnection(const void **attr, CGSConnectionID *id);


+(void)initialize
{
	NSMutableDictionary *defaultValues = [ NSMutableDictionary dictionary];
	[defaultValues setObject:[NSNumber numberWithInt:30] forKey:ABL_MaxMsgShow];
	[defaultValues setObject:[NSNumber numberWithFloat:0] forKey:ABL_Transparency];
	[defaultValues setObject:[NSNumber numberWithInt:10] forKey:ABL_RefreshInterval];
	[defaultValues setObject:@"" forKey:ABL_LoginString];
	[defaultValues setObject:[NSNumber numberWithInt:0] forKey:ABL_AlwaysOnTop];
	[defaultValues setObject:[NSNumber numberWithInt:0] forKey:ABL_HideAfterSendMsg];
	[defaultValues setObject:[NSNumber numberWithInt:1] forKey:ABL_HideGrowl];
	[defaultValues setObject:[NSNumber numberWithInt:1] forKey:ABL_HideIconBadge];
	[defaultValues setObject:[NSNumber numberWithInt:1] forKey:ABL_ShowYoutube];
	[[NSUserDefaults standardUserDefaults] registerDefaults:defaultValues];
}

- (id)init
{
  if (self = [super init]) {
    operationLock = [[NSLock alloc] init];
		
		blipMessages =[[NSMutableArray alloc] init];
    
		msgViews = [[NSMutableArray alloc] init];
		
		//userNames = [[NSMutableArray alloc] init];
		NSString *path = [[AppController appSupportDir] stringByAppendingPathComponent:BLIP_USERS_PATH];
		userNames = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
		if (userNames ==nil)
			userNames = [[NSMutableArray alloc] init];
		
		
		NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
		[nc addObserver:self
           selector:@selector(setOpacity:)
               name:ABL_TransparencyChangedNotification
             object:nil];
		
		[nc addObserver:self
          selector:@selector(handleReplyClicked:)
               name:ABL_ReplyClickedNotification
             object:nil];
    
		[nc addObserver:self
           selector:@selector(handleQuoteClicked:)
               name:ABL_QuoteClickedNotification
             object:nil];
		
		[nc addObserver:self
           selector:@selector(handleDeleteMessageClicked:)
               name:ABL_DeleteMessageClickedNotification
             object:nil];
		
		
		[nc addObserver:self
           selector:@selector(handlePictureClicked:)
               name:ABL_PictureClickedNotification
             object:nil];
		
    [nc addObserver:self
           selector:@selector(handleYoutubePictureClicked:)
               name:ABL_YoutubePictureClickedNotification
             object:nil];
		
		[nc addObserver:self
           selector:@selector(handlePictureExitClicked:)
               name:ABL_PictureMouseExitNotification
             object:nil];
    
		[nc addObserver:self
           selector:@selector(sendMessage:)
               name:ABL_SendMessageNotification
             object:nil];
    
    [nc addObserver:self
           selector:@selector(hotKeyHandle:)
               name:ABL_HotKeyNotification
             object:nil];
		
		[nc addObserver:self
           selector:@selector(updatePropertiesFromDefaults:)
               name:ABL_UpdatePreferences
             object:nil];
		
		[nc addObserver:self
           selector:@selector(handleErrorNotification:)
            name:ABL_ErrorMessageNotification
             object:nil];
    
		[nc addObserver:self
           selector:@selector(deleteAttPicture:)
               name:ABL_PictureAttDeleteNotification
             object:nil];
		
		
		[nc addObserver:self
           selector:@selector(increaseFontSize:)
               name:ABL_CommandPlusNotification
             object:nil];
		
//		
		[nc addObserver:self
           selector:@selector(decreaseFontSize:)
               name:ABL_CommandMinusNotification
             object:nil];
		
		//wczytanie parametrow z user defaults
		NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

		[self setOpacity: [defaults floatForKey:ABL_Transparency]];
    
		[self setMaxMessagesShow:[defaults integerForKey:ABL_MaxMsgShow]];
    
		[self setRefreshInterval:[defaults integerForKey:ABL_RefreshInterval]];
    
		[self setUserLogin:[defaults objectForKey:ABL_LoginString]];
    
		[self setLastUpdateId:[defaults objectForKey:ABL_LastUpdateId]];
		
		[self setHideAfterSendMsg:[defaults integerForKey:ABL_HideAfterSendMsg]];
		
		NSNumber* number = nil;
		number = [defaults objectForKey:ABL_HideIconBadge];
		if (number !=nil){
			[self setHideIconBadge:[number intValue]];
		}else {
			[self setHideIconBadge:NO];
			[defaults setBool:hideIconBadge forKey:ABL_HideIconBadge];
		}
		number = nil;
		number = [defaults objectForKey:ABL_ShowYoutube];
		if (number !=nil){
			[self setShowYoutube:[number intValue]];
		}else {
			[self setShowYoutube:YES];
			[defaults setBool:showYoutube forKey:ABL_ShowYoutube];
		}
		
		[self setLastUpdateId:@"0"];
		[self initializeGrowl];
		[self setMessagesTypeVisible:AllMessagesVisible];
		lastTypeMsgShow = AllMessagesVisible;
    
		
		
		activeQuickLook = [[NSBundle bundleWithPath:@"/System/Library/PrivateFrameworks/QuickLookUI.framework"] load];
    if (!activeQuickLook) {
      activeQuickLook = [[NSBundle bundleWithPath:@"/System/Library/Frameworks/Quartz.framework/Frameworks/QuickLookUI.framework"] load];
      realQuickLook = YES;
    }
		[[[QLPreviewPanel sharedPreviewPanel] windowController] setDelegate:self];
    [[QLPreviewPanel sharedPreviewPanel] setDelegate:self];
    if (realQuickLook)  {
      previewURL = [MyPreviewItem new];
      [[QLPreviewPanel sharedPreviewPanel] performSelector:@selector(setDataSource:) withObject:self];
    }
		isFirstRun = YES;
		shortKeyCall = NO;
		queue = [[NSOperationQueue alloc] init];
    [queue setMaxConcurrentOperationCount:1];
		shared = self;
	}
	return self;
}
+ (id)shared;
{
  if (!shared) {
    [[AppController alloc] init];
  }
  return shared;
}
-(void)handleGrowlWasClicked:(NSNotification*)note
{
#ifdef __DEBUG__

	NSLog(@"helllo");

#endif	
}
- (void)initializeGrowl
{
	growlReady = YES;

	[ GrowlApplicationBridge setGrowlDelegate : self ];
}
-(void)initializeTimer
{
	
	if (timer !=nil){
    
		[timer invalidate];
		[timer release];
		timer = nil;
	}
  
	timer = [[NSTimer scheduledTimerWithTimeInterval:refreshInterval
                                            target:self
                                          selector:@selector(getUpdateMessage:)
                                          userInfo:nil
                                           repeats:YES] retain];
}

-(void)stopTimer
{
  
	if (timer){
		[timer invalidate];
		[timer release];
		timer = nil;
	}
}

OSStatus MyHotKeyHandler(EventHandlerCallRef nextHandler,EventRef theEvent,void *userData)
{
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
  EventHotKeyID hkCom;
	GetEventParameter(theEvent,kEventParamDirectObject,typeEventHotKeyID,NULL,
                    sizeof(hkCom),NULL,&hkCom);
	int l = hkCom.id;
	
	switch (l) {
		case 1: 
			[nc postNotificationName:ABL_HotKeyNotification object:nil];
			break;
    }
	return noErr;
}

-(void)awakeFromNib
{
	[[NSFontManager sharedFontManager] setDelegate:self];
  [self performSelectorOnMainThread:@selector(sharedFontPanel) withObject:nil
                      waitUntilDone:YES];
  [theFontPanel setDelegate:self];
  [theFontPanel setBecomesKeyOnlyIfNeeded:NO];
  
	[[scrollView horizontalScroller] setNeedsDisplay:YES];
	[scrollView setDrawsBackground:NO];
	
	[[scrollViewPriv horizontalScroller] setNeedsDisplay:YES];
	[scrollViewPriv setDrawsBackground:NO];
	
	[scrollView setHidden:NO];
	[scrollViewPriv setHidden:YES];
	
	[self checkLoginStatus];
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSNumber *number = [defaults objectForKey:ABL_AlwaysOnTop];
  
	[hudWindow setFloatingPanel:NO];
	if ([number intValue] == 0){
		[hudWindow setLevel:NSNormalWindowLevel];
	}else {
		[hudWindow setLevel:NSFloatingWindowLevel];
	}
  
	
	[hudWindow setCollectionBehavior:NSWindowCollectionBehaviorMoveToActiveSpace];
	[hudWindow setDelegate:self];
  
	[homeButton setFrame:NSMakeRect(10, 9, [homeButton frame].size.width, [homeButton frame].size.height+4)];
	[refreshButton setFrame:NSMakeRect(330, 7, [refreshButton frame].size.width+6, [refreshButton frame].size.height+4)];
	[allBlipsButton setFrame:NSMakeRect(100, 9, 86,23)];
	[directedBlipsButton setFrame:NSMakeRect(186, 9, 86,23)];
	refreshIndicator = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(336,13, 15, 15)];
	
	
	
	[refreshIndicator setStyle:NSProgressIndicatorSpinningStyle];
	[refreshIndicator setControlSize:NSSmallControlSize];
	[refreshIndicator setDisplayedWhenStopped:NO];
	[pictureView addSubview:refreshIndicator];
	[pictureView addSubview:homeButton];
	[pictureView addSubview:refreshButton];
	[pictureView addSubview:allBlipsButton];
	[pictureView addSubview:directedBlipsButton];
	[allBlipsButton setState:NSOnState];
	[directedBlipsButton setState:NSOffState];
	[directedBlipsButton setEnabled:NO];
	
	messangerView = [[NSImageView alloc] initWithFrame:NSMakeRect(0, 0, 100, 100)];
	[messangerView setImage:[NSImage imageNamed:@"ablip_128"]];
	
	[self blockTextBox];
	
	[self setMessagesTypeVisible:AllMessagesVisible];
	
  
	[self hideRefreshButton];
	[refreshButton setImagePosition:NSImageOnly];
  
	NSRect rect = NSMakeRect(0, 0, 351, 437);
	updView = [[VBoxView alloc] initWithFrame:rect];
	privView = [[VBoxView alloc] initWithFrame:rect];
	[scrollView setDocumentView:updView];
	[scrollViewPriv setDocumentView:privView];
  
	[self showMessanger:@"Ściąganie wiadomości z kokpitu"];
	
	//Register the Hotkeys
	EventHotKeyRef gMyHotKeyRef;
	EventHotKeyID gMyHotKeyID;
	EventTypeSpec eventType;
	eventType.eventClass=kEventClassKeyboard;
	eventType.eventKind=kEventHotKeyPressed;
	InstallApplicationEventHandler(&MyHotKeyHandler,1,&eventType,NULL,NULL);
	gMyHotKeyID.signature='htk1';
	gMyHotKeyID.id=1;
	RegisterEventHotKey(7, cmdKey+optionKey, gMyHotKeyID, 
                      GetApplicationEventTarget(), 0, &gMyHotKeyRef);
  
  
//	gMyHotKeyID.signature = 'cmd+';
//	gMyHotKeyID.id = 2;
//	RegisterEventHotKey(24, cmdKey, gMyHotKeyID, 
//                      GetApplicationEventTarget(), 0, &gMyHotKeyRef);
//	
//	gMyHotKeyID.signature = 'cmd-';
//	gMyHotKeyID.id = 3;
//	RegisterEventHotKey(27, cmdKey, gMyHotKeyID, 
//                      GetApplicationEventTarget(), 0, &gMyHotKeyRef);
}


-(IBAction)showPreferencePanel:(id)sender
{ 
	if (!preferenceController){
		preferenceController = [[PreferenceController alloc]init];
	}
	
	//[[preferenceController window] setLevel:NSScreenSaverWindowLevel];
	[preferenceController showWindow:self];	
}

-(void)dealloc
{
	if (userLogin){
		[userLogin release];
		userLogin=nil;
	}
	if(userPassword){
		[userPassword release];
		userPassword = nil;
	}
	if(blipMessages){
		[blipMessages release];
		blipMessages=nil;
	}
	if(userNames){
		[userNames release];
		userNames=nil;
	}
	if(msgViews){
		[msgViews release];
		msgViews=nil;
	}
	if (preferenceController){
		[preferenceController release];
		preferenceController = nil;
	}
	if (lastUpdateId){
		[lastUpdateId release];
		lastUpdateId  = nil;
	}
	if (timer){
		[timer invalidate];
		[timer release];
		timer = nil;
	}
  
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
  [nc removeObserver:self];
	[super dealloc];
}

#pragma mark Properties
-(void)setUserLogin:(NSString*)userName;
{
	[userName retain];
	[userLogin release];
	userLogin = userName;
}
-(NSString*)userLogin
{
	return userLogin;
}
-(void)setUserPassword:(NSString*)passwd
{
	[passwd retain];
	[userPassword release];
	userPassword = passwd;
}
-(NSString*)userPassword
{
	return userPassword;
}

-(void)setLastUpdateId:(NSString*)value
{
	[value retain];
	[lastUpdateId release];
	lastUpdateId = value;
	//NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	//[defaults setObject:lastUpdateId forKey:ABL_LastUpdateId];
  
}
-(void)setMessagesTypeVisible:(int)value
{
	messagesTypeVisible = value;
	//[self setViewsInScrollView];
}

#pragma mark buttons_clicks
-(IBAction)openDashboard:(id)sender
{
	
	NSString *path = [NSString stringWithFormat:@"http://www.blip.pl/users/%@/dashboard", userLogin];
	NSURL *url = [NSURL URLWithString:path];
  [[NSWorkspace sharedWorkspace] openURL:url];
}
-(void)openUserDashboard:(NSString*)userToDisplay
{
	NSString *path = [NSString stringWithFormat:@"http://www.blip.pl/users/%@/dashboard", userToDisplay];
	NSURL *url = [NSURL URLWithString:path];
  [[NSWorkspace sharedWorkspace] openURL:url];
	//
  //	NSArray* urls = [ NSArray arrayWithObject:
  //					 [ NSURL URLWithString:url ]];
  //	
  //	BOOL opened = [[ NSWorkspace sharedWorkspace ]
  //				   openURLs:urls
  //				   withAppBundleIdentifier:nil
  //				   /* use default system bindings */
  //				   options:NSWorkspaceLaunchWithoutActivation
  //				   additionalEventParamDescriptor:nil
  //				   launchIdentifiers:nil ];
}
-(IBAction)allBlipsClick:(id)sender
{
	[allBlipsButton setState:NSOnState];
	[directedBlipsButton setState:NSOffState];
	[scrollView setHidden:NO];
	[scrollViewPriv setHidden:YES];
	//[scrollView setDocumentView:nil];
	//[scrollView setDocumentView:updView];
	/*[self setMessagesTypeVisible:AllMessagesVisible];
   if ([self changeVisibleMessagesTo:messagesTypeVisible]==TRUE){
   
   }*/
}
-(IBAction)directedBlipClick:(id)sender
{
	if ([directedBlipsButton isEnabled] ==NO)
		return;
	[directedBlipsButton setState:NSOnState];
	[allBlipsButton setState:NSOffState];
	[scrollView setHidden:YES];
	[scrollViewPriv setHidden:NO];
  
	//[scrollView setDocumentView:nil];
	//[scrollView  setDocumentView:privView];
	/*[self setMessagesTypeVisible:PrivateMessagesVisible];
   if ([self changeVisibleMessagesTo:messagesTypeVisible]==TRUE){
   
   }*/
} 

#pragma mark methods
-(void)showMessanger:(NSString*)textToShow
{
	
  NSRect frame  =	[[scrollView contentView] frame];
	[messangerView setImage:[NSImage imageNamed:@"grafikaIntro"]];
	NSSize imageSize = [[messangerView image] size];
	float x = frame.size.width/2 - imageSize.width/2;
	float y = frame.size.height/2 -imageSize.height/2 -4;
	[messangerView setFrame:NSMakeRect(x, y, imageSize.width, imageSize.height)];
	
	//ustawienie textu
	/*NSTextView* textView = [[NSTextView alloc] initWithFrame:NSMakeRect(10, 10, 30, 30)];
   
   [textView setTypingAttributes:[MessageView blipTextAttributes]];
   //	[textView setDrawsBackground:NO];
   [textView setEditable:NO];
   //[textView setSelectable:YES];
   [textView setRichText:NO];
   
   
   NSAttributedString* attributedBody = [[NSAttributedString alloc] initWithString: textToShow];
   NSTextStorage* textStorage = [textView textStorage];
   [textStorage beginEditing];
   [textStorage appendAttributedString:attributedBody];
   [textStorage endEditing];
   
   [messangerView addSubview:textView];
   */
	[messangerView setAutoresizingMask:    40];
	[[scrollView contentView] addSubview:messangerView];
  
}
-(void)hideMessanger
{
	[messangerView removeFromSuperview];
}
-(void)addAttachmentToBox
{
	
	[[hudWindow contentView] addSubview:[textBox attView]];
}
-(void)sendMessage:(NSNotification*)note
{
	
	SendMessageOperation *plo = [[SendMessageOperation alloc] initWithLock:operationLock];
	[queue addOperation:plo];
	[plo release];
  //[self getUpdateMessage:nil];
	return;
	
}

-(IBAction)getAvatar:(id)sender
{
#ifdef __DEBUG__

	NSLog(@"dzialam");

#endif
  
  
	
}
-(IBAction)manualRefresh:(id)sender
{
#ifdef __DEBUG__

	NSLog(@"reczny refresh");

#endif
  [self performSelectorOnMainThread:@selector(enableBlurForWindow:) withObject:hudWindow waitUntilDone:NO];
	[self getUpdateMessage:nil];
}
-(void)getUpdateMessage:(NSNotification*)note
{
	if ([self isFirstRun])
		[self performSelectorOnMainThread:@selector(enableBlurForWindow:) withObject:hudWindow waitUntilDone:NO];
	DownloadUpdatesOperation *plo = [[DownloadUpdatesOperation alloc] initWithType:withoutReset operationLock:operationLock];
	[queue addOperation:plo];
	[plo release];
	
	
}
-(void)deleteBlipMessages:(NSRange)atRange
{
	NSString *path;
	int indexToDelete = atRange.location;
	if ([blipMessages count]>=atRange.length && atRange.length >0){
		for (int i=0; i < atRange.length; i++){
			path = [AppController appSupportDir];
			if ([[blipMessages objectAtIndex:indexToDelete] picturePath] !=nil){
				path = [path stringByAppendingPathComponent:[[blipMessages objectAtIndex:indexToDelete] picturePath]];
				[self deleteFileAtPath:path];
			}
			
		}
		[blipMessages removeObjectsInRange:atRange];
	}
	
}

-(void)tryRefreshView:(NSString*)msgId
{
	[self setViewsInScrollView];
  
}

-(BOOL)changeVisibleMessagesTo:(int)visibleMsgType
{
  
	if (lastTypeMsgShow != visibleMsgType){
#ifdef __DEBUG__

		//	NSLog(@"change visible messages To %d", visibleMsgType);

#endif
		//skladanie
		NSRect frame;
		float startHeight = 0;
		int index =[msgViews count]-1;
		int indexPrivate =[privateMsgIndexes count]-1;
		float windowheight = [[scrollView contentView] frame].size.height *2;
		int viewsInWindow = 0;
		if (visibleMsgType == PrivateMessagesVisible){
			if ([privateMsgIndexes count] >0){
				
				
				for (MessageView *view in [msgViews reverseObjectEnumerator]){
					frame = [view frame];
					
					if (windowheight >0){
						windowheight -= frame.size.height;
						viewsInWindow++;
					}
					
					if (indexPrivate >=0 && [[privateMsgIndexes objectAtIndex:indexPrivate]intValue]  == index ){
						indexPrivate--;
            
						[view setNextFrame:NSMakeRect(10, startHeight, frame.size.width, frame.size.height)];
						
						startHeight += frame.size.height;
					} else {
            
						[view setNextFrame:NSMakeRect(10, startHeight, frame.size.width,0)];
						
					}
					index--;
          
					
				}
				[NSAnimationContext beginGrouping];
				[[NSAnimationContext currentContext] setDuration:0.9f];
				for (MessageView *view in [msgViews reverseObjectEnumerator] ){
          
					if (viewsInWindow>=0){
						[[view animator] setFrame:[view nextFrame]];
						viewsInWindow--;
					}else{
						[view  setFrame:[view nextFrame]];
					}
					
				}
				[NSAnimationContext endGrouping];		
				float he = [hudWindow frame].size.height - [bottom image].size.height;
				if (startHeight < he)
					startHeight = he;
				frame = [[scrollView documentView] frame];
				[[[scrollView documentView]animator] setFrame:NSMakeRect(0, 0, BLIP_WIDTH,
                                                                 startHeight)];
			}
			else {
				[directedBlipsButton setEnabled:NO];
			}
      
		}else {
			startHeight = 0;
			for (MessageView *view in [msgViews reverseObjectEnumerator]){
				frame = [view frame];
				
				if (windowheight >0){
					windowheight -= frame.size.height;
					viewsInWindow++;
				}
				if ([privateMsgIndexes count]>0){
					
				} else {
					[directedBlipsButton setEnabled:NO];
				}
        
				index--;
				
				startHeight += [view defaultFrame].size.height;
			}
			
      [[[scrollView documentView]animator] setFrame:NSMakeRect(0, 0, BLIP_WIDTH, startHeight)];
			[NSAnimationContext beginGrouping];
			[[NSAnimationContext currentContext] setDuration:0.9f];
			for (MessageView *view in [msgViews reverseObjectEnumerator]){
				if (viewsInWindow>=0){
					[[view animator] setFrame:[view defaultFrame]];
					viewsInWindow--;
				}else{
					[view  setFrame:[view defaultFrame]];
				}
				
				//[[view animator] setFrame:[view defaultFrame]];
        
			}
			[NSAnimationContext endGrouping];
		}
		lastTypeMsgShow = visibleMsgType;
		return TRUE;
	}
	return FALSE;
}
-(void)setViewsInScrollView
{
	[messangerView setImage:nil];
#ifdef __DEBUG__

	//NSLog(@"content  = %f , %f ",  [[scrollView contentView] frame].size.width,[[scrollView contentView] frame].size.height);

#endif
	int currentMaxMessagesShow =[self maxMessagesShow];
  
  
	if (!msgViews){
		msgViews = [[NSMutableArray alloc] init];
	}
	privateMsgIndexes = nil;
	if (!privateMsgIndexes){
		privateMsgIndexes = [[NSMutableArray alloc] init];
	}
	
#ifdef __DEBUG__

  NSLog(@"liczba msg  na poczatku %d", [blipMessages count]);

#endif
	
	//[directedBlipsButton setEnabled:NO];
	
	//jesli widoki puste dodanie od razu wszystkich
	MessageView *mView;
	NSString *msgType;
	//NSMutableArray* addedMsg = [[NSMutableArray alloc] init];
	int msgAdded=0;
	int index =0 ;
  
	if ([blipMessages count] > 0){
		
		for (BlipMessage* msg in blipMessages )
		{
			mView = [[MessageView alloc] initWithFrame:NSMakeRect(10, 0, BLIP_VIEW_WIDTH, BLIP_VIEW_HEIGHT)];
      
			[mView setBlipMsg:msg];	
			//[updView addItem:mView];
			[updView insertItem:mView atIndex:0];
			//sprawdzenie czy skierowana do mnie 
			msgType = [msg msgType];
			msgAdded++;
			
			if ([[msgType stringValue] isMatchedByRegex:ABL_REGEX_TO_ME_TYPES]){
				if ([msg recipientName] ==nil){
#ifdef __DEBUG__

					NSLog(@"recipient = nil");

#endif
				} else
					if ([[msg recipientName] isEqualToString:[self userLogin]]){
						mView = [[MessageView alloc] initWithFrame:NSMakeRect(10, 0, BLIP_VIEW_WIDTH, BLIP_VIEW_HEIGHT)];
						[mView setBlipMsg:msg];	
						[directedBlipsButton setEnabled:YES];
						//[privView addItem:mView];
						[privView insertItem:mView atIndex:0];
					}
			}
      
			
			index++;
		}		
		
	}
#ifdef __DEBUG__

	NSLog(@"liczba msg %d", [blipMessages count]);

#endif
	if (blipMessages){
		[blipMessages release];
		blipMessages = nil;
	}
#ifdef __DEBUG__

	NSLog(@"osatni po petli %@", [updView lastUpdateId]);

#endif
#ifdef __DEBUG__

	//NSLog(@"liczba dodanych  = %d , do mnie %d ", msgAdded, msgToMeAdded);

#endif
#ifdef __DEBUG__

	//NSLog(@"done");

#endif
	[updView adjustItemsCount:currentMaxMessagesShow];
	[privView adjustItemsCount:currentMaxMessagesShow];
	
	
	if ([hudWindow isKeyWindow] ==NO && msgAdded >0 && [self hideIconBadge] == YES){
		NSString *sCount = [[[NSApplication sharedApplication]  dockTile] badgeLabel];
		int count = 0;
		count = [sCount intValue];
		count += msgAdded;
		[[[NSApplication sharedApplication] dockTile] setBadgeLabel: [[NSNumber numberWithInt:count ] stringValue]];
	}
  
	if ([self isFirstRun] == YES){
		[self hideMessanger];
		[self setIsFirstRun:NO];
	}
	
  
  
	if ([self textBoxBocked]==YES){
		[self resetTextBox];
	}
	[self unHideRefreshButtton];
	[self initializeTimer];
#ifdef __DEBUG__

	//NSLog(@"updateo = %d", [updView msgCount]);

#endif
#ifdef __DEBUG__

  //NSLog(@"priv = %d", [privView msgCount]);

#endif
	return;
	
	
}

-(void)setOpacity:(float)value
{
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	
	NSNumber *number = [defaults objectForKey:ABL_Transparency];
	value 	=1- [number floatValue];
	
	if (value > 1.0){
		opacity = 1.0;
	}else if (value <0.5)
	{
		opacity = 0.5;
	}
	else{
		opacity = value;
	}
	for (int i=0; i < [msgViews count]; i++) {
		[[msgViews objectAtIndex:i] setOpacity:opacity];
	}
	[hudWindow setAlphaValue:opacity];
}
-(void)checkVisibleMessagesCount
{
	
}
-(void)hideRefreshButton
{
  
	[refreshIndicator startAnimation:self];
	[refreshButton setHidden:YES];
	
}
-(void)unHideRefreshButtton
{
  
	[refreshIndicator stopAnimation:self];
	[refreshButton setHidden:NO];
}
-(NSString*)checkDownloadData:(NSData*)data
{
	
	NSString* dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];	
	[dataString autorelease];
	
	if ([BlipErrors findError:data] == YES){
		
		data = nil;
		
		return nil;
	}
	
	return 	dataString;
}
-(void)readSubscriptions:(NSData*)data
{
	NSString* respString = [self checkDownloadData:data];
#ifdef __DEBUG__

	NSLog(@"%@", respString);

#endif
  
	if (!respString){
#ifdef __DEBUG__

    NSLog(@"I wypadam");

#endif
		return;
	}
	
	if (respString){
		NSMutableArray *jsonValues = [respString JSONValue];
		NSMutableDictionary *dict;
		if (!jsonValues){
#ifdef __DEBUG__

			NSLog(@"jsonValues array is empty!!");

#endif
		}else {
			int i;
			NSString *userName;
			
			for (i =[jsonValues count]-1; i >=0; i--){				
				dict = [jsonValues objectAtIndex:i];
#ifdef __DEBUG__

				//NSLog(@"dict = %@", dict);

#endif
				
				userName = [dict objectForKey:USER_PATH_NAME];
				userName = [userName lastPathComponent];
				if(userName !=nil && [userNames containsObject:userName]==NO){
					[userNames addObject:userName];
				}
				
			}
			
			//zapisanie nazw user'ow
			NSMutableArray* temp = [[NSMutableArray alloc] initWithArray:[userNames sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]];
			if (userNames){
				[userNames  release];
				userNames = nil;
			}
			userNames = temp;
			
			int counter =3;
			NSString *path = [[AppController appSupportDir] stringByAppendingPathComponent:BLIP_USERS_PATH];
			while (counter > 0){
				if ([NSKeyedArchiver archiveRootObject:userNames toFile:path] == YES)
					break;
				usleep(1000);
				counter--;
			}
			
		}
		jsonValues = nil;
		
	}
	
	return;
}

-(void)msgRecipientNotExist
{
	[self initializeTimer];
	[self unHideRefreshButtton];
	[textBox markNotExistedRecipient];
	[textBox setEditable:TRUE];
	[self setTextBoxBocked:NO];
}

-(void)resetTextBox
{
	[textBox setString:@""];
	[textBox setDraggedImagePath:@""];
	[textBox setEditable:YES];
	[textBox setSelectable:YES];
	[self setTextBoxBocked:NO];
}
-(void)blockTextBox
{
	[textBox setEditable:NO];
	[textBox setSelectable:NO];
	[self setTextBoxBocked:YES];
}
-(void)sendRequestWithSubscription
{
  
	DownloadSubscriptionOperration *plo = [[DownloadSubscriptionOperration alloc] init];
  
	[queue addOperation:plo];
	[plo release];
}

#pragma mark loginPanel

-(void)checkLoginStatus
{
	@try{
#ifdef __DEBUG__

    NSLog(@"loginstatus");

#endif
    //[self setUserLogin:@""];
    if ([userLogin isEqualToString:@""]==NO && [AGKeychain checkForExistanceOfKeychainItem:KeyChainItemName
                                                                              withItemKind:KeyChainItemKind 
                                                                               forUsername:userLogin] >0) {
      [self setUserPassword:[self getPasswordFromKeychainForLogin:userLogin]];
    }  else {
      
      [NSApp runModalForWindow:loginWindow];
      [loginWindow close];
      [loginWindow release];
      loginWindow = nil;
      if ([AGKeychain checkForExistanceOfKeychainItem:KeyChainItemName
                                         withItemKind:KeyChainItemKind 
                                          forUsername:userLogin] >0 ){
        
        [self setUserPassword:[self getPasswordFromKeychainForLogin:userLogin]];
        
      }
    }
    [self sendRequestWithSubscription];
    
    //ToDo
    [self getUpdateMessage:nil];
    ////[refreshButton performClick:self];
    [self hideRefreshButton];
	}
	@catch (NSException* ex) {
		[NSApp stopModalWithCode:NSOKButton];
	}
}

-(IBAction)trySaveToKeyChain:(id)sender
{
	NSString *log = [loginField stringValue];
	NSString *passwd = [passwordField stringValue];
	
	if ([log isEqualToString:@""] || [passwd isEqualToString:@""] ){
#ifdef __DEBUG__

		NSLog(@"Login i/lub haslo nie moga byc puste");

#endif
		
		
	}else {
		[self modifyItemFromKeychain:log password:passwd];
		userLogin = log;
		NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
		[defaults setObject:userLogin forKey:ABL_LoginString];
		[NSApp stopModal];
	}
}
-(void)modifyItemFromKeychain:(NSString*)newLogin password:(NSString*)passwd
{
	
	
	BOOL doesItemExisit = [AGKeychain checkForExistanceOfKeychainItem:KeyChainItemName
                                                       withItemKind:KeyChainItemKind 
                                                        forUsername:newLogin ];							
	NSString *passwdToEncode  = [NSString stringWithFormat:@"%@:%@", newLogin, passwd];
	NSData *passwdData = [passwdToEncode dataUsingEncoding:NSUTF8StringEncoding];
	passwdToEncode = [passwdData encodeBase64];
	
	if (doesItemExisit) {
		BOOL result = [AGKeychain modifyKeychainItem:KeyChainItemName
                                    withItemKind:KeyChainItemKind
                                     forUsername:newLogin
                                 withNewPassword:[passwdData encodeBase64]];
		if (!result){
			[self displayAlertWithMessageText:@"Nieudana próba modyfikacji danych w Pęku kluczy"];
		}
	}
	else {
		BOOL result = [AGKeychain addKeychainItem:KeyChainItemName
                                 withItemKind:KeyChainItemKind
                                  forUsername:newLogin
                                 withPassword:[passwdData encodeBase64]];
		if (!result) {
			[self displayAlertWithMessageText:@"Nieudana próba dodania danych do Pęku kluczy"];
		}
	}
}

- (NSString*)getPasswordFromKeychainForLogin:(NSString*)searchLogin
{
	NSString *passwordFound = nil;
	BOOL doesItemExisit = [AGKeychain checkForExistanceOfKeychainItem:KeyChainItemName
                                                       withItemKind:KeyChainItemKind
                                                        forUsername:searchLogin];
	if (doesItemExisit) {
		passwordFound = [AGKeychain getPasswordFromKeychainItem:KeyChainItemName 
                                               withItemKind:KeyChainItemKind
                                                forUsername:searchLogin];
		//return passwordFound;
	} else{
		[self displayAlertWithMessageText:@"Pęk kluczy: Brak dostępu"];
		return nil;
	}
	if (passwordFound ==nil){
		[self displayAlertWithMessageText:@"Pęk kluczy: Brak dostępu"];
		//[NSApp presentError:[NSError errorWithDomain:@"Pęk kluczy: Brak hasła" code:1 userInfo:nil]];
		return nil;
	} else {
		return passwordFound;
	}
}
-(void)handleErrorNotification:(NSNotification*)note
{
	
	NSString *error = [[note userInfo] objectForKey:ErrorDescription];
	[self displayAlertWithMessageText:error];
}
-(void)displayAlertWithMessageText:(NSString *)messageText
{
	NSAlert *alert = [[[NSAlert alloc] init] autorelease];
	[alert addButtonWithTitle:@"Ok"];
	[alert setMessageText:messageText];
	[alert setAlertStyle:NSWarningAlertStyle];
	[alert beginSheetModalForWindow:hudWindow modalDelegate:self didEndSelector:nil contextInfo:nil]; 
}
#pragma mark handling_icons_clicked
-(void)handleReplyClicked:(NSNotification*)note 
{
	NSString *messageTo = [[note userInfo] objectForKey:ABL_USER_INFO_QUOTE];
	NSString *matchString = @"^ *>{1,2}[^ ]+";
	NSString *messageText = [textBox stringValue];
	if ([messageText isMatchedByRegex:matchString]){
		[textBox setStringValue: [messageText stringByReplacingOccurrencesOfRegex:matchString withString:messageTo]];
	}else {
		[textBox setStringValue:[NSString stringWithFormat:@"%@ %@", messageTo, messageText]];
	}
	[hudWindow makeFirstResponder:textBox];
  
}
-(void)handleQuoteClicked:(NSNotification*)note
{
	NSString *quoteString  = [[note userInfo] objectForKey:ABL_USER_INFO_QUOTE];
	[textBox addQuote:quoteString];
  //	NSString *prevText = [textBox stringValue];
  //	[textBox setStringValue:[NSString stringWithFormat:@"%@%@", prevText, quoteString]];
	[hudWindow makeFirstResponder:textBox];
  
}
-(void)handleDeleteMessageClicked:(NSNotification*)note
{
	
	NSString *relativePath  = [[note userInfo] objectForKey:ABL_USER_INFO_DELETE];
	NSURLRequest *urlRequest = [[BLP_URLRequestUpdate alloc] initDeleteMethodWithAuth:userPassword :relativePath];
#ifdef __DEBUG__

	//NSLog(@"sending delete message with path:%@", relativePath);

#endif
  
	NSData *urlData;
	NSURLResponse *responce;
	NSError *error;
  
	urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&responce error:&error];
	//TODO dorobic obsluge bledow z dataString
	[urlRequest release];
	urlRequest = nil;
  
	[updView deleteMessageWithId:[NSString stringWithFormat:@"^%@$", [relativePath lastPathComponent]]];
	[privView deleteMessageWithId:[NSString stringWithFormat:@"^%@$", [relativePath lastPathComponent]]];
	//[self displayAlertWithMessageText:@"Wiadomość została usunięta z serwera (pozostaje jednak w widoku - poprawa w nast. aktualizacji"];
	return;
	//
	//na razie takie proste wyszukiwanie
	NSString *msgIdToDelete =[NSString stringWithFormat:@"^%@$", [relativePath lastPathComponent]];
	for (int i=0; i < [blipMessages count]; i++){
		if ([[[[blipMessages objectAtIndex:i] msgId] stringValue] isMatchedByRegex:msgIdToDelete]){
			
			[self deleteBlipMessages:NSMakeRange(i, 1)];
			break;
		}
	}
  //NSRect frame;
//  float height;
//  NSView* foundview = nil;
//  for (MessageView* view in msgViews) {
//    if ([[[view blipMsg] msgId] isMatchedByRegex:msgIdToDelete]) {
//      foundview = view;
//      break;
//    }
//  }
//  [msgViews removeObject:foundview];
//  [foundview removeFromSuperview];
//  [self setViewsInScrollView];
//  return;
	NSRect frame;
	int index = [msgViews count];
	for (MessageView *view in [msgViews reverseObjectEnumerator]){
		index--;
		float height;
		if ([[[[view blipMsg] msgId] stringValue] isMatchedByRegex:msgIdToDelete]){
#ifdef __DEBUG__

			//NSLog(@"messages %d", messagesTypeVisible);

#endif
			if (messagesTypeVisible == AllMessagesVisible){
				int indexFrom = index-1;
#ifdef __DEBUG__

				//NSLog(@"indexFrom = %d", indexFrom);

#endif
				if (indexFrom >= 0){
					height = [view frame].size.height;
          
					MessageView *mView;
					[NSAnimationContext beginGrouping];
					[[NSAnimationContext currentContext] setDuration:0.4f];
					for (int i=indexFrom ; i >= 0; i--){
						mView = [msgViews objectAtIndex:i];
						frame = [mView frame];
						[mView setDefaultFrame:NSMakeRect(frame.origin.x, frame.origin.y - height, frame.size.width, frame.size.height)];
            
						
						[[mView animator]setFrame:NSMakeRect(frame.origin.x, frame.origin.y - height, frame.size.width, frame.size.height )];
						
					}
					[NSAnimationContext endGrouping];
				}
			} else {
				int indexFrom = index-1;
				for (NSNumber *number in privateMsgIndexes){
          
#ifdef __DEBUG__

					//NSLog(@"indeks pry: %d z wiad :%@", [number intValue], [[[msgViews objectAtIndex:x] blipMsg]body]);

#endif
				}
				int indexPriv = [privateMsgIndexes count] -1;
				for (NSNumber *number  in [privateMsgIndexes reverseObjectEnumerator]){
					
					
					if ([number intValue] == index){
						indexPriv--;
						break;
					}
					indexPriv--;
				}
				
#ifdef __DEBUG__

				//NSLog(@"indexPriv = %d", indexPriv);

#endif
				if (indexFrom >= 0){
					height = [view frame].size.height;
					
					MessageView *mView;
					[NSAnimationContext beginGrouping];
					[[NSAnimationContext currentContext] setDuration:0.4f];
					for (int i=indexFrom ; i >= 0; i--){
						mView = [msgViews objectAtIndex:i];
						frame = [mView defaultFrame];
#ifdef __DEBUG__

						//NSLog(@"bylo : %f", [mView defaultFrame].origin.y);

#endif
						[mView setDefaultFrame:NSMakeRect(frame.origin.x, frame.origin.y - height, frame.size.width, frame.size.height)];
#ifdef __DEBUG__

						//NSLog(@"jest po przesuwie : %f", [mView defaultFrame].origin.y);

#endif
						frame= [mView frame];
						
						if (indexPriv >=0 && i == [[privateMsgIndexes objectAtIndex:indexPriv] intValue]){
#ifdef __DEBUG__

							//NSLog(@"index to schrink %d", i);

#endif
							indexPriv--;
							
							[[mView animator]setFrame:NSMakeRect(frame.origin.x, frame.origin.y - height, frame.size.width, frame.size.height )];
							
						}
					}
					[NSAnimationContext endGrouping];
				}
			}
			int indexToDel = [privateMsgIndexes count]-1;
			for (NSNumber *number  in [privateMsgIndexes reverseObjectEnumerator]){
				
				
				if ([number intValue] == index){
					[privateMsgIndexes removeObjectAtIndex:indexToDel];
					break;
				}
				indexToDel--;
			}
			
			
			[view removeFromSuperview];
			[msgViews removeObjectAtIndex:index];
      
      
			frame = [[scrollView documentView] frame];
      
			float x=  frame.size.height - height;
      //			[[[scrollView documentView] animator]setFrame:NSMakeRect(frame.origin.x, frame.origin.y, frame.size.width , x)];
      
			NSClipView* newView= [[NSClipView alloc] initWithFrame:NSMakeRect(frame.origin.x, frame.origin.y, frame.size.width , x)];
      [newView setDrawsBackground:NO];
			for (MessageView *view in msgViews){
				[newView addSubview:view];
				[view release];
			}
			[scrollView setDocumentView:nil];
			[scrollView setDocumentView:newView];
			
			if ([privateMsgIndexes count] < 1)
				[self allBlipsClick:self];
			break;
		}
	}
	
	//[self setViewsInScrollView];
  
}
-(void)handleYoutubePictureClicked:(NSNotification*)note
{
#ifdef __DEBUG__

  NSLog(@"Handluje");

#endif
	NSString* urlPath = [[note userInfo] objectForKey:@"path"];
	if (urlPath){
		NSURL *url = [NSURL URLWithString: urlPath];
		if (url) {
      NSString* bundle;
      if ([[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:@"com.apple.QuickTimePlayerX"]) {
        bundle = @"com.apple.QuickTimePlayerX";
      } else {
        bundle = @"com.apple.quicktimeplayer";
      }
      [[NSWorkspace sharedWorkspace] openURLs:[NSArray arrayWithObject:url]
                      withAppBundleIdentifier:bundle
                                      options:NSWorkspaceLaunchAsync
               additionalEventParamDescriptor:nil
                            launchIdentifiers:nil];
    }
			
	}	
}
-(void)handlePictureClicked:(NSNotification*)note
{
	//NSData *picture = [[note userInfo] objectForKey:@"picture"];
	//NSString *path  = [AppController picturesDownloadDir];
	//path = [path stringByAppendingPathComponent:[[note userInfo] objectForKey:@"path"]];
	NSString *path = [[note userInfo] objectForKey:@"path"];
	float x=0,y=0;
	
  if (realQuickLook) {
    previewURL.previewItemURL = [NSURL fileURLWithPath:path];
  }
  
	x = [[[note userInfo] objectForKey:@"pointX"] floatValue] ;
	y =  [[[note userInfo] objectForKey:@"pointY"] floatValue] ;
	NSPoint p = [NSEvent mouseLocation];
	quickLookRect = NSMakeRect(p.x, p.y, 10,10);
	//path = [path stringByAppendingPathComponent:@"pict"];
#ifdef __DEBUG__

	//NSLog(@"picture = %@", path);

#endif
	
	[self userDidPressSpaceInOutlineView:path];
	//quickLookRect = NSMakeRect(0, 0, 0, 0);
}
-(void)handlePictureExitClicked:(NSNotification*)note
{
#ifdef __DEBUG__

  NSLog(@"Exit");

#endif
	if([[QLPreviewPanel sharedPreviewPanel] isOpen])
		[[QLPreviewPanel sharedPreviewPanel] closeWithEffect:2];
  
}
-(void)deleteAttPicture:(NSNotification*)note
{
	if ([self textBoxBocked] ==NO)
		[textBox setDraggedImagePath:@""];
}
-(void)updatePropertiesFromDefaults:(NSNotification*)note
{
	
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	
	NSNumber *number = [defaults objectForKey:ABL_MaxMsgShow];
	[self setMaxMessagesShow:[number intValue]];
	
	number = [defaults objectForKey:ABL_Transparency];
	[self setOpacity:[number floatValue]];
	
	number = [defaults objectForKey:ABL_RefreshInterval];
	[self setRefreshInterval:[number intValue]];
	number = [defaults objectForKey:ABL_AlwaysOnTop];
	
	if ([number intValue] == 0){
		[hudWindow setLevel:NSNormalWindowLevel];
	}else {
		[hudWindow setLevel:NSFloatingWindowLevel];
		//[hudWindow  setLevel:NSScreenSaverWindowLevel];
    
	}
	number = [defaults objectForKey:ABL_HideAfterSendMsg];
	[self setHideAfterSendMsg:[number intValue]];
	
	number = [defaults objectForKey:ABL_HideGrowl];
	[self setHideGrowlNotif:[number intValue]];
	
	number = [defaults objectForKey:ABL_HideIconBadge];
	[self setHideIconBadge:[number intValue]];
	
	number = [defaults objectForKey:ABL_ShowYoutube];
	[self setShowYoutube:[number intValue]];
	
	[self setViewsInScrollView];
}
-(void)handleTextMesgChanged:(NSNotification*)note
{
	//int textLength = [[textBox stringValue] length];
}
-(IBAction)hideShowApp:(id)sender
{
	[self hotKeyHandle:nil];
}
-(void)hotKeyHandle:(NSNotification*)note
{
	[NSApp isHidden]==NO?[NSApp hide:self]:[NSApp activateIgnoringOtherApps:YES];
	shortKeyCall = YES;
}
-(void)hideApp
{
	[NSApp hide:self];
}

#pragma mark font_size_handling
- (void)sharedFontPanel
{
  theFontPanel = [[NSFontManager sharedFontManager] fontPanel:YES];
}



- (IBAction)ShowFontPanel:(id)sender
{
  [theFontPanel orderFront:sender];
}

- (void)changeFont:(id)sender
{
#ifdef __DEBUG__

	NSLog(@"changeFont");

#endif
}

- (IBAction)increaseFontSizeAction:(id)sender {
  [[NSNotificationCenter defaultCenter] postNotificationName:ABL_CommandPlusNotification object:nil];
}

- (IBAction)decreaseFontSizeAction:(id)sender {
  [[NSNotificationCenter defaultCenter] postNotificationName:ABL_CommandMinusNotification object:nil];
}

-(IBAction)increaseFontSize:(id)note
{
	[updView incrementFontSize];
	[privView incrementFontSize];
}
-(IBAction)decreaseFontSize:(id)note
{
	[updView decrementFontSize];
	[privView decrementFontSize];
}

#pragma mark GrowlMethods
- (NSDictionary*) registrationDictionaryForGrowl
{
	// For this application, only one notification is registered
	NSArray* defaultNotifications = [NSArray arrayWithObjects:GrowlDefaultNotification, nil];
	NSArray* allNotifications = [NSArray arrayWithObjects:GrowlDefaultNotification, nil];
	
	NSDictionary* growlRegistration = [NSDictionary dictionaryWithObjectsAndKeys: 
									   defaultNotifications, GROWL_NOTIFICATIONS_DEFAULT,
									   allNotifications, GROWL_NOTIFICATIONS_ALL, nil];
	
	return growlRegistration;
}
- (void) growlIsReady
{
	// Only get called when Growl is starting. Not called when Growl is already running so we leave growlReady to YES by default...
	growlReady = YES;
}
- (NSString *) applicationNameForGrowl
{
	return @"ABlip";
}
- (void) growlNotificationWasClicked:(id)clickContext
{
#ifdef __DEBUG__

	NSLog(@"kliknales %@", clickContext);

#endif
	[textBox setStringValue:clickContext];
	[NSApp activateIgnoringOtherApps:YES];
}
//
//- (void) growlNotificationTimedOut:(id)clickContext
//{
//	if (alertTimedOut == nil)
//		alertTimedOut = [[NSAlert alloc] init];
//	
//	NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:clickContext];
//	NSString* message = [NSString stringWithFormat:notificationTimedOutMessage, (int)interval];
//	
//	[alertTimedOut setMessageText:message];
//	[alertTimedOut beginSheetModalForWindow:hudWindow modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];
//}

-(void)sendGrowlMessage:(BlipMessage*)message
{
	NSString *context;
	NSString *notifyTitle;
	BOOL withPicture = [message pictureData]==nil?NO:YES;
	if ([message userName] == nil){
#ifdef __DEBUG__

		NSLog(@"sendGr userName = nil");

#endif
	} else
	if ([[message userName] isEqualToString:userLogin] ==NO){
		if ([message msgType] == nil){
#ifdef __DEBUG__

			NSLog(@"send msgtype = nil");

#endif
		} else
			
		if ([[message msgType] isEqualToString:@"PrivateMessage"]==YES){
			context = [NSString stringWithFormat:@">>%@ ",[message userName]];
			if (withPicture)
				notifyTitle = @"Wiadomość prywatna od %@ [zdjęcie]:";
			else
				notifyTitle = @"Wiadomość prywatna od %@:";
		}else if ([[message msgType] isEqualToString:@"DirectedMessage"]==YES){
			context = [NSString stringWithFormat:@">%@ ",[message userName]];
			if (withPicture)
				notifyTitle = @"Wiadomość od %@ [zdjęcie]:";
			else {
				notifyTitle = @"Wiadomość od %@:";
			}

		}		else{ 
		
			context = @"";
			if ([message userSex] !=nil)
			{
				if([[message userSex] isEqualToString:@"m"]){
					if (withPicture)
						notifyTitle = @"%@ napisał [zdjęcie]:";	
					else
						notifyTitle = @"%@ napisał:";
				}
				else{
					if (withPicture)
						notifyTitle = @"%@ napisała [zdjęcie]:";
					else
						notifyTitle = @"%@ napisała:";
				}
			} else {
				if (withPicture)
					notifyTitle = @"%@ pisze [zdjęcie]:";
				else {
					notifyTitle = @"%@ pisze:";
				}

			}
		}
	} else {
			context = [NSString stringWithFormat:@">>%@ ",[message userName]];
			notifyTitle = @"Wiadomość wysłana";
	}
	NSImage* newImage = [[NSImage alloc] initWithContentsOfFile:[message userAvatarPath]];
  for (NSImageRep* rep in [newImage representations]) {
    [rep setSize:NSMakeSize(50, 50)];
  }
	[GrowlApplicationBridge
	 notifyWithTitle:[NSString stringWithFormat:notifyTitle, [message userName]]
	 description:[message body]
	 notificationName:GrowlDefaultNotification
	 iconData:[newImage TIFFRepresentation]
	 priority:2
	 isSticky:NO
	 clickContext:context]; 
  [newImage release];
}
-(void)sendGrowlDownloadingMsg
{
	[GrowlApplicationBridge
	 notifyWithTitle:[NSString stringWithFormat:@"ABlip"]
	 description:@"Pobieram wiadomości z kokpitu."
	 notificationName:GrowlDefaultNotification
	 iconData:nil
	 priority:2
	 isSticky:NO
	 clickContext:nil];
}
-(void)sendGrowlMoreMessages:(NSString*)moreMsgCount;
{
	[GrowlApplicationBridge
	 notifyWithTitle:[NSString stringWithFormat:@"ABip"]
	 description:[NSString stringWithFormat:@"Jest jeszcze %@ wiadomości.", moreMsgCount]
	 notificationName:GrowlDefaultNotification
	 iconData:nil
	 priority:2
	 isSticky:NO
	 clickContext:nil];
}
- (NSString *)growlInstallationWindowTitle
{
	return [NSString stringWithString:@"Instalacja Growl"];
}

 
- (NSString *)growlUpdateWindowTitle
{
	return [NSString stringWithString:@"Okno aktualizacji"];
}
- (NSAttributedString *)growlInstallationInformation
{
	NSFont *font = [NSFont fontWithName:@"Helvetica" size:12.0];
	NSDictionary *attrsDictionary =
	[NSDictionary dictionaryWithObject:font
								forKey:NSFontAttributeName];


	return [[NSAttributedString alloc] initWithString:@"ABlip współpracuje z systemem powiadomień Growl. Dzięki Growl możesz ukryć okno programu a wiadomości z Blipa będą pojawiać się w prawym górnym narożniku ekranu i po chwili znikać."
										   attributes:attrsDictionary];
}
	/*
- (NSAttributedString *)growlUpdateInformation
{
	
}*/

#pragma mark file_dir_methods
+(NSString*)appSupportDir
{
	static NSString* supportDir  = nil;
	if (!supportDir){
		NSFileManager *fm = [NSFileManager defaultManager];
		NSString *path = [fm currentDirectoryPath];
		NSArray *appSupportDirs = NSSearchPathForDirectoriesInDomains (	 NSApplicationSupportDirectory,NSUserDomainMask,YES);
		if([appSupportDirs count]!=0){
			path = [NSString stringWithFormat:@"%@",[appSupportDirs objectAtIndex:0]];
			supportDir = [path stringByAppendingPathComponent:@"ABlip"];
		}else {
			supportDir =  path;
		}
	}
  
	return supportDir;
}
+(NSString*)picturesDownloadDir
{
	static NSString* pictDir  = nil;
	if (!pictDir){
		pictDir = [AppController appSupportDir];
		pictDir = [pictDir stringByAppendingPathComponent:PICTURE_DIR_NAME];
	}
	return pictDir;
}
-(void)deleteFileAtPath:(NSString*)path
{	
	
	NSFileManager *fm = [NSFileManager defaultManager];
	NSError *error;
	if ([fm fileExistsAtPath:path]==YES){
		if (![fm removeItemAtPath:path error:&error]){
			[self displayAlertWithMessageText:[error description]];
		}
	}
}
#pragma mark quickLook preview
// This is the delegate method
// It should return the frame for the item represented by the URL
// If an empty frame is returned then the panel will fade in/out instead
- (NSRect)previewPanel:(NSPanel*)panel frameForURL:(NSURL*)URL
{
	return quickLookRect;
}

- (NSRect) previewPanel: (id) panel sourceFrameOnScreenForPreviewItem: (id /*<QLPreviewItem>*/) item {
  return quickLookRect;
}

- (NSInteger)numberOfPreviewItemsInPreviewPanel:(id)panel {
  return 1;
}

- (id /*<QLPreviewItem>*/)previewPanel:(id)panel previewItemAtIndex:(NSInteger)index {
  return previewURL;
}

- (BOOL)userDidPressSpaceInOutlineView:(NSString*)imagePath
{
	if(activeQuickLook)
	{
		// If the user presses space when the preview panel is open then we close it
		if([[QLPreviewPanel sharedPreviewPanel] isOpen]) {
      [[QLPreviewPanel sharedPreviewPanel] closeWithEffect:2];
      return YES;
    }
		
		
		NSArray *url =[NSArray arrayWithObject: [NSURL fileURLWithPath:imagePath]];
    //[[QLPreviewPanel sharedPreviewPanel] setURLs:url preservingDisplayState:YES];
    if (realQuickLook) {
      [[QLPreviewPanel sharedPreviewPanel] performSelector:@selector(reloadData)];
      [[QLPreviewPanel sharedPreviewPanel] performSelector:@selector(refreshCurrentPreviewItem)];
    } else {
      [[QLPreviewPanel sharedPreviewPanel] setURLs:url currentIndex:0 preservingDisplayState:YES];
    }
    
		[[QLPreviewPanel sharedPreviewPanel]  makeKeyAndOrderFrontWithEffect:2];
    
    
	}
	return YES;
}
- (void)quickLookSelectedItems:(NSString*)imagePath
{
	if (activeQuickLook){
    
		if([[QLPreviewPanel sharedPreviewPanel] isOpen])
			[[QLPreviewPanel sharedPreviewPanel] closeWithEffect:2];
		if(activeQuickLook)
		{
			NSArray *url =[NSArray arrayWithObject: [NSURL fileURLWithPath:imagePath]];
			// The code above just gathers an array of NSURLs representing the selected items,
			// to set here
			[[QLPreviewPanel sharedPreviewPanel] setURLs:url currentIndex:0 preservingDisplayState:YES];
			[[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFrontWithEffect:1];
      
		}
	}
}

#pragma mark dock_Icon_drop
- (BOOL)application:(NSApplication *)sender openFile:(NSString *)path
{
	[textBox setDraggedImagePath:path];
	return YES;
}
#pragma mark window_notifications
- (void)windowDidBecomeKey:(NSNotification *)notification
{
	[[[NSApplication sharedApplication] dockTile] setBadgeLabel:@""];
}
- (BOOL)windowShouldClose:(NSNotification *)notification
{
	[self hotKeyHandle:nil];
	return NO;
}
-(void)showWindow
{
	[hudWindow setLevel:NSScreenSaverWindowLevel];
}

- (void)enableBlurForWindow:(NSWindow *)window
{
	
	CGSConnectionID _myConnection;
	uint32_t __compositingFilter;
	
	int __compositingType = 1; // Apply filter to contents underneath the window, then draw window normally on top
	
	/* Make a new connection to CoreGraphics, alternatively you could use the main connection*/
	
	CGSNewConnection(NULL , &_myConnection);
	
	/* The following creates a new CoreImage filter, then sets its options with a dictionary of values*/
	
	CGSNewCIFilterByName (_myConnection, (CFStringRef)@"CIGaussianBlur", &__compositingFilter);
	NSDictionary *optionsDict = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:3.0] forKey:@"inputRadius"];
	CGSSetCIFilterValuesFromDictionary(_myConnection, __compositingFilter, (CFDictionaryRef)optionsDict);
	
	/* Now just switch on the filter for the window */
	
	CGSAddWindowFilter(_myConnection, [window windowNumber], __compositingFilter, __compositingType );
}
#pragma mark buttonShortcuts
-(IBAction)changeMessageToType:(id)sender
{
	
	[textBox changeMessageToType];
}
-(IBAction)hideShowGrowl:(id)sender
{
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[self setHideGrowlNotif:[self hideGrowlNotif]== YES?NO:YES];
	[defaults setObject:[NSNumber numberWithInt:[self hideGrowlNotif]] forKey:ABL_HideGrowl];
	[preferenceController setHideGrowl:[self hideGrowlNotif]];
	
}
-(void)createBlipMsg
{
	blipMessages = [[NSMutableArray alloc] init];
}
@end

